package Area;

import org.apache.hadoop.io.DoubleWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;
import java.io.IOException;

public class PriceByAreaMapper extends Mapper<LongWritable, Text, Text, DoubleWritable> {

    private static final int BUILDING_AREA_INDEX = 5;
    private static final int PRICE_INDEX = 14;

    @Override
    protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
        String line = value.toString();
        if (line.isEmpty()) return;

        String[] fields = line.split(",");

        if (fields.length > Math.max(BUILDING_AREA_INDEX, PRICE_INDEX)) {
            try {
                double buildingArea = Double.parseDouble(fields[BUILDING_AREA_INDEX].trim());
                double pricePerSquareMeter = Double.parseDouble(fields[PRICE_INDEX].trim());

                String areaRange = getAreaRange(buildingArea);
                if (areaRange != null) {
                    context.write(new Text(areaRange), new DoubleWritable(pricePerSquareMeter));
                }
            } catch (NumberFormatException e) {
                System.err.println("解析数据时出错，位于行数为: " + line);
            }
        }
    }

    private String getAreaRange(double buildingArea) {
        // 定义建筑面积区间
        for (int i = 30; i <= 290; i += 10) {
            if (buildingArea >= i && buildingArea < i + 10) {
                return String.format("%d平方米-%d平方米", i, i + 10);
            }
        }
        return null;
    }
}

